package com.macro.mall.boot.wechat.miniapp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import com.macro.mall.boot.wechat.props.WxMiniAppProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序配置
 *
 * @author xuyanjun
 * @date 2019-07-09
 */
@Slf4j
@Configuration
public class WxMiniAppConfig {

    /**
     * 微信服务
     */
    private static Map<Integer, WxMaService> WX_MA_SERVICE_MAP = new HashMap<>();


    /**
     * 获取微信服务
     *
     * @param businessAppId 业务AppId
     * @return 微信服务
     */
    public static WxMaService getWxMaServiceByBusinessAppId(int businessAppId) {
        Assert.isTrue(businessAppId > 0, "业务AppId不能为空。");

        WxMaService wxMaService = WX_MA_SERVICE_MAP.get(businessAppId);
        if (wxMaService == null) {
            log.error("未配置对应的业务appId:" + businessAppId);

            throw new IllegalArgumentException("未配置对应的业务appId。");
        }

        return wxMaService;
    }

    @Profile(value = {"dev", "test"})
    @Bean
    public Inner wxMiniAppPropertiesDev() {
        // 千猪小程序(10001)
        WxMiniAppProperties wxMiniAppProperties = new WxMiniAppProperties();
        wxMiniAppProperties.setAppId("wxd4fabc97c46c0196")
                .setSecret("8e6078aaf602ef32af11448366375fa1");

        buildMaService(10001, wxMiniAppProperties);

        return new Inner();
    }

    @Profile(value = {"pro"})
    @Bean
    public Inner wxMiniAppPropertiesPro() {
        // 千猪小程序(10001)
        WxMiniAppProperties wxMiniAppProperties = new WxMiniAppProperties();
        wxMiniAppProperties.setAppId("wx0db9ab8309db2dd4")
                .setSecret("3f9be49c9397721cece8c6ff8893c1e3");

        return new Inner();
    }

    private void buildMaService(int appId, WxMiniAppProperties wxMiniAppProperties) {
        WxMiniAppInRedisConfig config = new WxMiniAppInRedisConfig(wxMiniAppProperties.getAppId());
        config.setAppid(wxMiniAppProperties.getAppId());
        config.setSecret(wxMiniAppProperties.getSecret());
        config.setToken(wxMiniAppProperties.getToken());
        config.setAesKey(wxMiniAppProperties.getAesKey());
        config.setMsgDataFormat(wxMiniAppProperties.getMsgDataFormat());

        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(config);

        WX_MA_SERVICE_MAP.put(appId, wxMaService);
    }

    private static class Inner {

    }
}
